import Vue from 'vue'
import Router from 'vue-router'
import Login from './components/Login.vue'
import Home from './components/Home.vue'
import Test from './components/test.vue'
import Welcome from './components/Welcome.vue'
import Users from './components/user/Users'
import PersonAuthority from './components/PersonAuthority'
import Rights from './components/Rights'
import FanKui from './components/FanKui'
Vue.use(Router)

const router = new Router({
  mode: 'history',
  routes: [
    { path: '/', redirect: '/login' },
    { path: '/login', component: Login, meta: { title: '请登录' } },
    {
      path: '/home',
      component: Home,
      redirect: '/welcome',
      children: [
        { path: '/welcome', component: Welcome },
        { path: '/users', component: Users },
        { path: '/roles', component: PersonAuthority },
        { path: '/rights', component: Rights }
      ]
    },
    { path: '/test', component: Test },
    { path: '/fankui', component: FanKui }
  ]
})
// 挂载路由导航守卫(控制权限) 如果用户没有登录 需要重新导航到登录页
// 路由拦截
router.beforeEach((to, from, next) => {
  if (to.path === '/test') return next()
  else if (to.path === '/login') return next()
  const tokenStr = window.sessionStorage.getItem('token')
  if (!tokenStr) return next('/login')
  next()
})

router.afterEach((to, from) => {
  document.title = to.meta.title || '电商系统'
})
export default router
